package com.zy.explore.wechat.util;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Arrays;

/**
 * description 微信签名工具类
 *
 * @author ZY
 * @date 2021年05月25日 00:04
 */

public class WechatSignUtil {

    public static boolean checkSignature(String token, String signature, String timestamp, String nonce) {
        //定义数组存放token，timestamp,nonce
        String[] arr = {token, timestamp, nonce};
        //对数组进行排序
        Arrays.sort(arr);
        //生成字符串
        StringBuilder sb = new StringBuilder();
        for (String s : arr) {
            sb.append(s);
        }
        //sha1加密,网上均有现成代码
        String temp = getSha1(sb.toString());
        //将加密后的字符串，与微信传来的加密签名比较，返回结果
        return temp.equals(signature);
    }

    /**
     * sha1加密
     *
     * @param str 待加密字符串
     * @return 返回加密后的字符串
     */
    public static String getSha1(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
            mdTemp.update(str.getBytes(StandardCharsets.UTF_8));
            byte[] md = mdTemp.digest();
            int j = md.length;
            char buf[] = new char[j * 2];
            int k = 0;
            for (byte byte0 : md) {
                buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
                buf[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(buf);
        } catch (Exception e) {
            return null;
        }
    }
}